<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
        left: 0;
        top: 0;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
    <!-- <script>
      var boxEle = document.querySelector(".box");
      //   var timer = setInterval(function () {
      //     var num = parseInt(getComputedStyle(boxEle)["left"]);
      //     if (num == 300) {
      //       clearInterval(timer);
      //     } else {
      //       num += 10;
      //       boxEle.style.left = num + "px";
      //     }
      //   }, 100);
      function move(ele, target, dir, cb) {
        function fn() {
          var num = parseInt(getComputedStyle(ele)[dir]);

          var speed = target < num ? -3 : 3;
          if (num == target) {
            console.log("停止了");
            cb && cb();
          } else {
            num += speed;
            ele.style[dir] = num + "px";
            requestAnimationFrame(fn);
          }
        }

        fn();
      }

      move(boxEle, 300, "left", function () {
        console.log("传入的函数");
        move(boxEle, 300, "top", function () {
          move(boxEle, 0, "left", function () {
            move(boxEle, 0, "top");
            console.log("所有运动完成");
          });
        });
      });
    </script> -->
    <script>
      var boxEle = document.querySelector(".box");
      function move(ele, target, dir) {
        function fn() {
          var num = parseInt(getComputedStyle(ele)[dir]);
          var speed = target < num ? -3 : 3;
          if (num == target) {
            console.log("停止了");
          } else {
            num += speed;
            ele.style[dir] = num + "px";
            requestAnimationFrame(fn);
          }
        }
        fn();
      }
      move(boxEle, 300, "left");
    </script>
  </body>
</html>
